package utilx

import (
	"encoding/base64"
	"strings"
)

type Base64 struct {
	base64Table string
	hashHeader  string
	hashFooter  string
}

/**
 *
 */
func NewBase64() *Base64 {
	const (
		//BASE64字符表,不要有重复 ~!@#$%^&*()_+`1234567890-=qwertyuiop[]\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:"zxcvbnm,./ZXCVBNM<>?.
		//base64Table        = "<>:;',./?~!@#$CDVWX%^&*ABYZabcghijklmnopqrstuvwxyz01EFGHIJKLMNOPQRSTU2345678(def)|{}[]9/"
		base64Table = "`CDVkl*mnB~abc|qrK-xyz$01E.ijF}G]AvH@IghM>NOs_uJP^RU2,34;ST56!78"
		hashHeader  = "zh.ife.iya"
		hashFooter  = "09.O25.O20.78"
	)

	return &Base64{base64Table: base64Table, hashHeader: hashHeader, hashFooter: hashFooter}
}

/**
 * base64加密
 */
func (a *Base64) Encode(str string) string {
	str = strings.TrimSpace(str)
	coder := base64.NewEncoding(a.base64Table)

	src := []byte(a.hashHeader + str + a.hashFooter)
	return coder.EncodeToString(src)
}

/**
 * base64解密
 */
func (a *Base64) Decode(str string) (string, error) {
	coder := base64.NewEncoding(a.base64Table)

	src, err := coder.DecodeString(str)
	if err != nil {
		return "", err
	}

	res := string(src[len(a.hashHeader) : len(src)-len(a.hashFooter)])

	return res, nil
}
